import {message} from 'antd'
export function serialize(obj) {
    let ret = []
    for(let key in obj) {
        if(['', undefined,null].includes(obj[key]))
            continue
        if(obj[key] instanceof Array) {
            obj[key].forEach(item => {
                ret.push(`${encodeURIComponent(key)}[]=${encodeURIComponent(item)}`)
            })
        }else {
            ret.push(`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
        }
    }
    return ret.length?ret.join('&'):''
}
export function get(url, data, headers = []) {
    return new Promise((resolve, reject) => {
        fetch(url + '?' + serialize(data), {
            method: 'GET',
            headers: headers,
            dataType: 'json'
        }).then(response => response.json())
            .then(json => {
                if(json.code === 0 || json.code === '0') {
                    resolve(json)
                }else if(json.code === -401 || json.code === '-401'){
                    message.warning(json.msg)
                    setTimeout(()=>{
                        window.location.href = json.url?json.url:'/login'
                    },3000)
                    reject({type:401,error:json.msg})
                }else if(json.code === -403 || json.code === '-403') {
                    message.warning(json.msg)
                    reject({type:403, error:json.msg})
                }else {
                    reject({type:1,error:json.msg})
                }
            }).catch(err => {
            reject({type:500, error:err})
        })
    })
}
export  function post(url, data, headers){
    return new Promise((resolve, reject) => {
        fetch(url,{
            method: 'POST',
            body:JSON.stringify(data),
        }).then(response => response.json())
            .then(json => {
                console.log(json)
                if(json.code === 0 || json.code === '0') {
                    resolve(json)
                }else if(json.code === -401 || json.code === '-401'){
                    message.warning(json.msg)
                    setTimeout(()=>{
                        window.location.href = json.url?json.url:'/login'
                    },3000)
                    reject({type:401,error:json.msg})
                }else if(json.code === -403 || json.code === '-403') {
                    message.warning(json.msg)
                    reject({type:403, error:json.msg})
                }else {
                    reject({type:1,error:json.msg})
                }
            }).catch(err => {
                reject({type:500, error:err})
        })
    })
}

